package com.main.crossdomaineventmanagement.event.config;

import com.main.common.utils.exceptions.StackTraceLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.TopicConfig;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExt;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Slf4j
@Configuration
public class TopicInitializer {
    @Value("${rocketmq.name-server}")
    private String nameServer;
    @Value("${rocketmq.broker-address}")
    private String brokerAddress;

    @PostConstruct
    public void initTopic() throws Exception {
        DefaultMQAdminExt admin = new DefaultMQAdminExt();
        admin.setNamesrvAddr(nameServer);
        admin.start();
        if(!admin.fetchAllTopicList().getTopicList().contains("SAGA_ROLLBACK_TOPIC")) {
            try {
                // Check if topic exists
                TopicConfig topicConfig = new TopicConfig("SAGA_ROLLBACK_TOPIC"); // 创建TopicConfig对象并设置主题名称
                topicConfig.setReadQueueNums(4); // 设置读队列数量，根据需要设置
                topicConfig.setWriteQueueNums(4); // 设置写队列数量，根据需要设置
                topicConfig.setPerm(6); // 设置权限，例如可读写
                topicConfig.setTopicSysFlag(11);
                admin.createAndUpdateTopicConfig(brokerAddress, topicConfig); // 创建主题
                log.info("成功创建主题SAGA_ROLLBACK_TOPIC");
            } catch (MQClientException e) {
                // Handle exception
                StackTraceLog stackTraceLog = new StackTraceLog();
                stackTraceLog.saveStackTraceLog(e);
            } finally {
                admin.shutdown();
            }
        }else{
            log.info("已存在主题SAGA_ROLLBACK_TOPIC");
        }
    }
}